package com.ysd.lis.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.cri.CriCriticalReport;
import com.ysd.lis.entity.cri.CriUserVsDept;
import com.ysd.lis.entity.cri.CriWarningConfig;
import com.ysd.lis.request.cri.CriticalSendMess;
import com.ysd.lis.service.SysOrgDepartmentService;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.service.cri.CriCriticalReportService;
import com.ysd.lis.service.cri.CriWarningConfigService;
import com.ysd.lis.socket.MessageTemplate;
import com.ysd.lis.socket.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * his30分钟未推送危急值
 *
 * @author wanghao
 * @create 2024/9/5 0005
 */
@Component("critical")
@Slf4j
public class CriticalReport {
    @Autowired
    private CriCriticalReportService criticalReportService;
    @Autowired
    private CriWarningConfigService warningConfigService;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgDepartmentService sysOrgDepartmentService;

    public void criticalReportPush() {
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        // 30 分钟前的时间
        // LocalDateTime thirtyMinutesAgo = now.minus(30, ChronoUnit.MINUTES);
        // lambdaQueryWrapper.gt(CriCriticalReport::getCreateTime, thirtyMinutesAgo);
        List<CriWarningConfig> warningConfigs = warningConfigService.list(new LambdaQueryWrapper<CriWarningConfig>().eq(CriWarningConfig::getDelFlag, 0));
        Map<String, List<String>> macUrlMap = warningConfigs.stream()
                .collect(Collectors.groupingBy(CriWarningConfig::getUserInfo,
                        Collectors.mapping(CriWarningConfig::getMacUrl, Collectors.toList())));

        LambdaQueryWrapper<CriCriticalReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.and(it->it.in(CriCriticalReport::getStateCode, 0).or().isNull(CriCriticalReport::getStateCode));
        List<CriCriticalReport> criticalReports = criticalReportService.list(lambdaQueryWrapper);
        for (CriCriticalReport criticalReport : criticalReports) {
            List<SysUser> macUrlAllByDept =new ArrayList<>();
            switch (criticalReport.getStateCode()) {
                //通知医生
                case 0:
                    macUrlAllByDept = getDoctorMacUrlAllByDept(criticalReport.getReportDeptNo());
                    break;
            }
            // 推送websocket
            MessageTemplate messageTemplate = new MessageTemplate();
            // 类型为2是推送,3是销毁
            messageTemplate.setType("2");
            CriticalSendMess criticalSendMess = new CriticalSendMess();
            BeanUtil.copyProperties(criticalReport, criticalSendMess);
            messageTemplate.setMessage(String.valueOf(criticalSendMess));
            // 根据被通知人编号 查询全科室的用户
            if (CollectionUtil.isNotEmpty(macUrlAllByDept)) {
                boolean havaUserInfo = false;
                for (SysUser sysUser : macUrlAllByDept) {
                    List<String> macUrlList = macUrlMap.get(sysUser.getUsername());
                    if (CollectionUtil.isNotEmpty(macUrlList)) {
                        havaUserInfo=true;
                        for (String macUrl : macUrlList) {
                            WebSocketUtils.sendMessage(macUrl, messageTemplate);
                        }
                    }else {
                        log.error("[{}]用户没有配置mac地址", sysUser.getUsername()+":"+sysUser.getRealname());
                    }
                }
                if (havaUserInfo){
                    criticalReport.setStateCode(20);
                    criticalReport.setDoctorReportTime(new Timestamp(System.currentTimeMillis()));
                    criticalReportService.updateById(criticalReport);
                }else {
                    log.error("没有找到被通知的医生,请维护医生用户的对照科室");
                }
            }else {
                log.error("没有找到用户信息,请维护用户表");
            }
        }
    }
    public List<SysUser> getDoctorMacUrlAllByDept(String deptCode) {
        if (StringUtils.isBlank(deptCode)){
            log.error("上报危急值没有科室信息");
            return null;
        }
        LambdaQueryWrapper<SysOrgDepartment> lambdaWrapper = new LambdaQueryWrapper();
        lambdaWrapper.eq(SysOrgDepartment::getCode, deptCode);
        lambdaWrapper.eq(SysOrgDepartment::getDelFlag, 0);
        List<SysOrgDepartment> list = sysOrgDepartmentService.list(lambdaWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            SysOrgDepartment sysOrgDepartment = list.get(0);
       /*     MPJLambdaWrapper<SysUser> mpjLambdaWrapper = new MPJLambdaWrapper();
            mpjLambdaWrapper.selectAll(SysUser.class);
            mpjLambdaWrapper.leftJoin(SysUserDept.class, p -> p.eq(SysUserDept::getUserId, SysUser::getId).eq(SysUserDept::getDelFlag, 0));
            mpjLambdaWrapper.leftJoin(SysUserRole.class, p -> p.eq(SysUserRole::getUserId, SysUser::getId).eq(SysUserRole::getDelFlag, 0));
            mpjLambdaWrapper.leftJoin(SysRole.class, p -> p.eq(SysUserRole::getRoleId, SysRole::getId).eq(SysRole::getDelFlag, 0));
            mpjLambdaWrapper.eq(SysUserDept::getDeptId, sysOrgDepartment.getId());
            mpjLambdaWrapper.eq(SysRole::getRoleName, "护士");
            List<SysUser> userList = sysUserService.list(mpjLambdaWrapper);*/
            MPJLambdaWrapper<SysUser> mpjLambdaWrapper = new MPJLambdaWrapper();
            mpjLambdaWrapper.distinct();
            mpjLambdaWrapper.selectAll(SysUser.class);
            mpjLambdaWrapper.leftJoin(CriUserVsDept.class, p -> p.eq(CriUserVsDept::getUsername, SysUser::getUsername).eq(CriUserVsDept::getDelFlag, 0));
            mpjLambdaWrapper.eq(CriUserVsDept::getDeptCode, sysOrgDepartment.getCode());
            List<SysUser> userList = sysUserService.list(mpjLambdaWrapper);
            return userList;
        }

        return null;
    }

}
